package com.jiuye.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuye.common.CustomException;
import com.jiuye.entity.Setmeal;
import com.jiuye.entity.SetmealDish;
import com.jiuye.entity.SetmealDto;
import com.jiuye.mapper.ISetmealMapper;
import com.jiuye.service.ISetmealDishService;
import com.jiuye.service.ISetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 添加套餐
 *
 * @author likeWen
 * @since 2022/11/4 15:57
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<ISetmealMapper, Setmeal> implements ISetmealService {
    @Autowired
    private ISetmealDishService setmealDishService;
    /**
     *添加套餐及菜品
     */
    @Override
    @Transactional//开启事务
    public void saveWithDish(SetmealDto setmealDto) {
        //1.保存套餐表
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        this.save(setmeal);
        //2.保存套餐和菜品的关系
            //先判断是否有数据
        if (CollectionUtils.isNotEmpty(setmealDto.getSetmealDishes())){
            //有数据的情况下，在做新增
            for (SetmealDish dish : setmealDto.getSetmealDishes()) {
                dish.setSetmealId(setmeal.getId());
            }
            //保存套餐和菜品的关系
            this.setmealDishService.saveBatch(setmealDto.getSetmealDishes());
        }
    }

    /**
     * 删除套餐，同时删除套餐及菜品的关系
     * @param ids
     */
    @Override
    @Transactional//开启事务
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        //查看起售状态
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);
        if (count > 0){
            throw  new CustomException("正在售卖，不可删除");
        }
        //删除套餐数据，操作setmeal表，执行删除操作
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> removeWrapper = new LambdaQueryWrapper<>();
        removeWrapper.in(SetmealDish::getSetmealId,ids);

        //删除套餐和菜品关联数据，操作setmeal_dish表，执行删除操作
        setmealDishService.remove(removeWrapper);
    }
}
